<template>
  <el-dialog :model-value="show" title="添加角色" @close="emit('hide')">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="账号：" prop="username">
        <el-input
          v-model="form.username"
          autocomplete="off"
          placeholder="请输入账号"
        />
      </el-form-item>
      <el-form-item label="姓名：" prop="nickName">
        <el-input
          v-model="form.nickName"
          autocomplete="off"
          placeholder="请输入姓名"
        />
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input
          v-model="form.email"
          autocomplete="off"
          placeholder="请输入邮箱"
        />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input
          v-model="form.password"
          autocomplete="off"
          placeholder="请输入密码"
          type="password"
          :disabled="id !== 0"
        />
      </el-form-item>
      <el-form-item label="备注：" prop="note">
        <el-input
          v-model="form.note"
          :rows="3"
          autocomplete="off"
          type="textarea"
          placeholder="用简单的语言来描述一下吧"
        />
      </el-form-item>
      <el-form-item label="是否启用">
        <el-radio-group v-model="form.status" class="ml-4">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button>取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage, FormInstance, ElMessageBox } from 'element-plus';
import { reactive, ref, watch } from 'vue';
import { getUserIdAPI, registerAPI, updateUserAPI } from './api';

// 控制对话框显隐
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  id: {
    type: Number,
    default: 0,
  },
});

watch(
  () => props.id,
  () => {
    if (props.id !== 0) {
      getUserIdAPI(props.id).then((res) => {
        if (res.code === 200) {
          Object.assign(form, res.data);
        }
      });
    }
  }
);

// 接收父组件自定义事件
const emit = defineEmits(['hide']);

// 添加账号 请求的参数
const form = reactive<IUserModel>({
  email: '',
  status: 99,
  nickName: '',
  note: '',
  password: '',
  username: '',
});

// 自定义邮箱校验
const validatorEmail = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback();
  } else if (!/^\w+[@]\w+[.]+\w+/.test(value)) {
    return callback(new Error('email不是一个合法的电子邮件地址'));
  } else {
    callback();
  }
};

// 表单校验
const rules = {
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  email: [{ validator: validatorEmail, trigger: 'change' }],
  note: [{ min: 1, message: '长度不能低于 1', trigger: 'change' }],
  nickName: [{ min: 1, message: '长度不能低于 1', trigger: 'change' }],
};

const formRef = ref<FormInstance>();

// 添加角色
const register = () => {
  // 用户二次确认
  ElMessageBox.confirm('此操作将添加当前用户信息, 是否继续?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    // 点击确认按钮
    .then(() => {
      registerAPI(form).then((res) => {
        // 添加成功
        if (res.code === 200) {
          emit('hide', true); //关闭对话框重新刷新数据
          formRef.value?.resetFields(); //重置表单字段
        }
      });
    })
    // 点击取消按钮
    .catch(() => {});
};

const editUser = () => {
  // 用户二次确认
  ElMessageBox.confirm('此操作将修改当前用户信息, 是否继续?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    // 点击确认按钮
    .then(() => {
      updateUserAPI(form).then((res) => {
        // 修改成功
        if (res.code === 200) {
          ElMessage.success('修改成功');
          formRef.value?.resetFields(); //重置表单字段
          emit('hide', true); //关闭对话框重新刷新数据
        }
      });
    })
    // 点击取消按钮
    .catch(() => {});
};

// 对表单数据进行校验
const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      // 如果id等于0就添加账号
      if (props.id === 0) {
        register();
      } else {
        // 编辑账号
        editUser();
      }
    } else {
      ElMessage.error('操作失败');
    }
  });
};
</script>
<style lang="less" scoped></style>
